// 彩票数据服务
import lotteryData from './data.js';

// 定义彩票数据接口
class LotteryService {
	// 获取彩票数据
	async fetchLotteryData() {
		try {
			// 使用导入的数据
			const data = this.parseLotteryData(lotteryData);
			return data;
		} catch (error) {
			console.error('获取彩票数据失败:', error);
			return [];
		}
	}

	// 解析彩票数据
	parseLotteryData(data) {
		const records = [];
		const lines = data.split('\n');

		for (const line of lines) {
			if (!line.trim()) continue;

			const parts = line.split(' ').filter(part => part !== '');
			if (parts.length < 7) continue; // 确保有足够的字段

			const issue = parts[0];
			const date = parts[1];
			// 提取号码 (第2到第6个字段)
			const numbers = parts.slice(2, 7).map(num => parseInt(num, 10));
			// 提取销售额 (第7个字段)
			const sales = parts.length > 7 ? parseInt(parts[7], 10) : undefined;
			// 提取注数 (第8个字段)
			const directBetCount = parts.length > 8 ? parseInt(parts[8], 10) : undefined;
			// 提取单注奖金 (第9个字段)
			const directBetPrize = parts.length > 9 ? parseInt(parts[9], 10) : undefined;
			// 提取特别号码 (第10个字段，如果有)
			const bonusNumber = parts.length > 10 ? parseInt(parts[10], 10) : undefined;

			records.push({
				issueNumber: issue,
				date: date,
				numbers: numbers,
				sales: sales,
				directBet: {
					count: directBetCount,
					prize: directBetPrize
				},
				bonusNumber: bonusNumber
			});
		}

		return records;
	}

	// 分析彩票数据
	analyzeLotteryData(data, usePermutationThree = false) {
		const numberCount = {};

		data.forEach(item => {
			const numbersToAnalyze = usePermutationThree ? item.numbers.slice(0, 3) : item.numbers;
			numbersToAnalyze.forEach(num => {
				if (numberCount[num]) {
					numberCount[num]++;
				} else {
					numberCount[num] = 1;
				}
			});
		});

		// 按出现次数排序
		const sortedNumbers = Object.entries(numberCount)
			.sort((a, b) => b[1] - a[1])
			.reduce((obj, [key, value]) => {
				obj[key] = value;
				return obj;
			}, {});

		return sortedNumbers;
	}

	// 按位置分析数字出现频率
	analyzeNumbersByPosition(data, usePermutationThree = false) {
		// 初始化每个位置的计数器
		const maxPositions = usePermutationThree ? 3 : 5;
		const positionCounts = {};

		// 初始化位置计数器
		for (let i = 1; i <= maxPositions; i++) {
			positionCounts[i.toString()] = {};
		}

		// 遍历数据，统计每个位置上的数字出现次数
		data.forEach(item => {
			const numbersToAnalyze = usePermutationThree ? item.numbers.slice(0, 3) : item.numbers;
			numbersToAnalyze.forEach((num, index) => {
				// 只统计前maxPositions个位置
				if (index < maxPositions) {
					const position = (index + 1).toString();
					if (positionCounts[position][num]) {
						positionCounts[position][num]++;
					} else {
						positionCounts[position][num] = 1;
					}
				}
			});
		});

		// 对每个位置的数字按出现次数排序
		for (const position in positionCounts) {
			positionCounts[position] = Object.entries(positionCounts[position])
				.sort((a, b) => b[1] - a[1])
				.reduce((obj, [key, value]) => {
					obj[key] = value;
					return obj;
				}, {});
		}

		return positionCounts;
	}

	// 查找最常出现的组合
	findMostFrequentCombinations(data, count = 5, usePermutationThree = false) {
		const combinationCounts = {};
		const maxPositions = usePermutationThree ? 3 : 5;

		data.forEach(item => {
			const combination = item.numbers.slice(0, maxPositions);
			const combinationStr = combination.join(',');
			if (combinationCounts[combinationStr]) {
				combinationCounts[combinationStr]++;
			} else {
				combinationCounts[combinationStr] = 1;
			}
		});

		// 按出现次数排序并返回前count个
		return Object.entries(combinationCounts)
			.sort((a, b) => b[1] - a[1])
			.slice(0, count)
			.map(([combination]) => combination.split(',').map(num => parseInt(num)));
	}

	// 生成多个可能的高几率组合
	generateHighProbabilityCombinations(data, count = 5, usePermutationThree = false) {
		// 过滤掉无效数据
		const validData = data.filter(item => {
			const requiredLength = usePermutationThree ? 3 : 5;
			// 确保numbers数组有足够元素，并且不全是0
			return item.numbers.length >= requiredLength && !item.numbers.slice(0, requiredLength).every(num => num === 0);
		});

		const combinations = [];
		const positionCounts = this.analyzeNumbersByPosition(validData, usePermutationThree);
		const totalDraws = validData.length;
		const maxPositions = usePermutationThree ? 3 : 5;

		// 生成指定数量的组合
		for (let i = 0; i < count; i++) {
			const combination = [];

			// 为每个位置选择一个出现频率较高的数字
			for (let j = 1; j <= maxPositions; j++) {
				const position = j.toString();
				const positionNumbers = Object.entries(positionCounts[position]);

				// 计算每个数字的概率
				const probabilities = positionNumbers.map(([num, count]) => {
					return {
						num: parseInt(num),
						probability: count / totalDraws
					};
				});

				// 基于概率权重随机选择一个数字
				const selectedNumber = this.selectByProbability(probabilities);
				combination.push(selectedNumber);
			}

			// 确保组合不重复
			if (!this.isCombinationExists(combinations, combination)) {
				combinations.push(combination);
			} else {
				// 如果组合重复，减少索引以重新生成
				i--;
			}
		}

		return combinations;
	}

	// 辅助方法：基于概率权重选择数字
	selectByProbability(numbers) {
		// 计算总概率
		const totalProbability = numbers.reduce((sum, num) => sum + num.probability, 0);

		// 生成随机数
		let random = Math.random() * totalProbability;

		// 基于概率选择数字
		for (const num of numbers) {
			random -= num.probability;
			if (random <= 0) {
				return num.num;
			}
		}

		// 如果随机数没有选中任何数字，返回概率最高的数字
		return numbers[0].num;
	}

	// 检查组合是否已存在
	isCombinationExists(combinations, newCombination) {
		return combinations.some(combination => 
			combination.length === newCombination.length && 
			combination.every((num, index) => num === newCombination[index])
		);
	}
}

// 创建服务实例
const lotteryService = new LotteryService();

// 默认导出服务对象
export default lotteryService;